'''
Created on May 5, 2011

@author: yc30v1m
'''

from suds.client import Client
from logging import getLogger


log = getLogger(__name__)

class sudsConnector(object):
    '''
    Usable Functions:
    1. execute (Pass all db Parameters)
    2. 
    '''
    conn = "null"
    soapUrl = "http://localhost:8090/connector?wsdl"
    __currentRow__ = 0
    __rowCount__ = ""
    __columnCount__ = ""
    __result__ = ""
    dbType = ""
    dbName = ""
    dbHost = ""
    dbUser = ""
    dbPass = ""
    dbQuery = ""
    dbPort = ""
    dbSchema = ""
    
    def __init__(self):
        pass
        
            
    def rowCount(self):
        self.__rowCount__ = len(self.__result__)
        return self.__rowCount__
    
    def columnCount(self):
        self.__columnCount__ = len(self.__result__[self.__currentRow__]['item'])
        return self.__columnCount__
    
    def hasNext(self):
        if self.__currentRow__ == self.__rowCount__ - 1:
            return False
        else:
            return True
    
    def getCurrentRow(self):
        return self.getRow()

    def getRow(self):
        if self.__currentRow__ < self.rowCount():
            return self.__result__[self.__currentRow__]['item']
        else:
            raise Exception('Current Row is Not Valid Row and is Not Active')
    
    def getColumnNames(self):
        colNamesList = []
        for names in self.getRow():
            colNamesList.append(names[0][0])
        return colNamesList
    
    def getRowValuesAsList(self, row):
        colValuesList = []
        for names in row:
            colValuesList.append(names[1][0])
        return colValuesList
    
    def getCurrentRowValuesAsList(self):
        return self.getRowValuesAsList(self.getRow())
    
    def getCurrentRowAsDict(self):
        row = {}
        for colName in self.getColumnNames():
            row[colName] = self.getColumnValueByName(colName)
        return row
    
    def getColumnValueByName(self, colName):
        try:
            
            for col in self.getRow():
                if col[0][0] == colName:
                    return col[1][0]
        except:
            raise Exception('"%s" is not a valid column Name, valid Values are %s' % (colName, self.getColumnNames()))
        
    def getColumnValueById(self, id):
        if id == self.columnCount() - 1:
            col = self.getRow()
            return col[id].value[0]
        raise Exception('"%s" is not a valid column Number, it should be LESS THAN %s' % (id, self.columnCount()))
    
    def getNextRow(self):
        if self.hasNext():
            self.moveNext()
            return self.getRow()
        else:
            return False
        
    def moveNext(self):
        if self.hasNext():
            self.__currentRow__ += 1
            
    def rewind(self):
        self.__currentRow__ = 0
    
    def getFirstRow(self):
        self.rewind()
        return self.__result__[self.__currentRow__]['item']
        
    def getLastRow(self):
        return self.__result__[self.rowCount() - 1]['item']
    
    ''' 
    Mapper Specific Functions
    execute will not be used in Mapper
    '''
    def execute(self, dbType, dbName, dbHost, dbUser, dbPass, dbQuery , dbPort="", dbSchema=""):
        try:
            if dbType == "" or dbName == "" or dbHost == "" or dbUser == "" or dbPass == "" or dbQuery == "":
                raise Exception("All or Any Required Parameters missing")                 
            elif dbSchema == "" and dbPort == "":
                self.__result__ = self.conn.service.dbExec(dbType, dbName, dbHost, dbUser, dbPass, dbQuery)
            elif dbSchema == "" and dbPort != "":
                self.__result__ = self.conn.service.dbExec(dbType, dbName, dbHost, dbUser, dbPass, dbQuery, dbPort)
            elif dbSchema != "" and dbPort != "":
                self.__result__ = self.conn.service.dbExec(dbType, dbName, dbHost, dbUser, dbPass, dbQuery, dbPort, dbSchema)
                             
            self.rowCount()
            self.columnCount()
        except:
            log.critical(" exec thor ")
            raise Exception('DbType = "%s" dbName = "%s", dbHost = "%s", dbUser = "%s", dbPass = "%s", dbQuery = "%s", dbPort = "%s", dbSchema = "%s" Unable to getSoap Results for ' % (dbType, dbName, dbHost, dbUser, dbPass, dbQuery, dbPort, dbSchema))
        
    def setConnectionUrl(self, connectionUrl):
        self.soapUrl = connectionUrl
        self.conn = Client(self.soapUrl)
        
    def connectTo(self, dbType, dbName, dbHost, dbUser, dbPass, dbPort="", dbSchema=""):
        self.dbType = dbType
        self.dbName = dbName
        self.dbHost = dbHost
        self.dbUser = dbUser
        self.dbPass = dbPass
        if dbPort == "" or dbPort == False:
            self.dbPort = ""
        else:
            self.dbPort = dbPort
        if dbSchema == "" or dbSchema == False:
            self.dbSchema = ""
        else:
            self.dbSchema = dbSchema
            
    def executeQuery(self, sQuery):
        self.execute(self.dbType, self.dbName, self.dbHost, self.dbUser, self.dbPass, sQuery, self.dbPort, self.dbSchema)
